package com.baidu.speech.restapi.ttsdemo;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.LinkedBlockingQueue;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;

public class AePlayWave extends Thread {
	private LinkedBlockingQueue<String> linkedBlockingQueue;

    private String filename;
    public AePlayWave(){
    	
    }
    public AePlayWave(LinkedBlockingQueue<String> lbq){
    	this.linkedBlockingQueue=lbq;
    }
    public AePlayWave(String wavfile) {
        filename = wavfile;

    }
    

    public String getFilename() {
		return filename;
	}
	public void setFilename(String filename) {
		this.filename = filename;
	}

	public synchronized void run() {

		String filename="";
		try {
			filename = linkedBlockingQueue.take();
		} catch (InterruptedException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		if(!filename.equals("")){
			File soundFile = new File(filename);

			// 获取音频输入流
			AudioInputStream audioInputStream = null;
			try {
				audioInputStream = AudioSystem.getAudioInputStream(soundFile);
			} catch (Exception e1) {
				e1.printStackTrace();
				return;
			}

			// 获取音频编码对象
			AudioFormat format = audioInputStream.getFormat();
			// 设置数据输入
			SourceDataLine auline = null;
			DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);

			try {
				auline = (SourceDataLine) AudioSystem.getLine(info);
				auline.open(format);
			} catch (Exception e) {
				e.printStackTrace();
				return;
			}

			auline.start();
			/*
			 * 从输入流中读取数据发送到混音器
			 */
			int nBytesRead = 0;
			byte[] abData = new byte[512];

			try {
				while (nBytesRead != -1) {
					// try {
					// Thread.currentThread().sleep(100);
					// } catch (InterruptedException e1) {
					// // TODO Auto-generated catch block
					// e1.printStackTrace();
					// }
					nBytesRead = audioInputStream.read(abData, 0, abData.length);
					if (nBytesRead >= 0)
						auline.write(abData, 0, nBytesRead);
				}
			} catch (IOException e) {
				e.printStackTrace();
				return;
			} finally {
				// 清空数据缓冲,并关闭输入
				auline.drain();
				auline.close();
			}
		}
		

	}
}

